<template>
  <view class="markdownTextArea">
    <view id="vditor"></view>
    <view v-if="loading" class="loadingClass">
      <u-loading size="24" color="#2979ff" />
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { toolbarConfig } from "./markdownTextUtils.js";

const props = defineProps({
  value: {
    type: String,
    required: true,
  },
});

let contentEditor = null;
const loading = ref(true);

onMounted(() => {
  uni
    .createSelectorQuery()
    .select(".markdownTextArea")
    .boundingClientRect((res) => {
      const height = res.height;
      contentEditor = new Vditor("vditor", {
        height: height || 360,
        toolbar: toolbarConfig({
          uploadImgClick: () => {
            uni.chooseImage({
              count: 1, //默认9
              sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
              sourceType: ["album", "camera "], //从相册或者相机选择
              success: (res) => {
                const file = res.tempFiles[0];
                if (file.size / 1024 / 1024 > 10) {
                  vk.toast("图片不能大于10M", "none");
                  return false;
                }
                uni.vk.uploadFile({
                  title: "文件上传中",
                  file,
                  success: function (res) {
                    console.log(res);
                    contentEditor.insertValue(`![${res.url}](${res.url})`);
                  },
                });
              },
              fail() {
                uni.showToast({
                  title: "未授权访问相册权限，请授权后使用",
                  icon: "none",
                });
              },
            });
          },
        }),
        toolbarConfig: {
          pin: false,
        },
        cache: {
          enable: false,
        },
        after: () => {
          loading.value = false;
          contentEditor.setValue(props.value || "");
        },
      });
    })
    .exec();
});

watch(
  () => props.value,
  (newValue) => {
    if (contentEditor) {
      contentEditor.setValue(newValue || "");
      console.log("watch props.value", newValue);
    }
  }
);

const getValue = () => {
  const value = contentEditor?.getValue();
  console.log(value);
  return value;
};

defineExpose({
  getValue,
});
</script>

<style scoped lang="scss">
.markdownTextArea {
  height: 100%;
  width: 100%;
  padding: 0 10px;
  position: relative;
  .loadingClass {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
    & > text {
      font-size: 14px;
      color: $u-tips-color;
      margin-left: 5px;
    }
  }
}
:deep(.vditor) {
  border: unset;
  .vditor-toolbar {
    border: unset;
  }
  .vditor-reset p {
    margin-bottom: 0.5em;
  }
}
</style>

<style></style>
